using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using CodeStory.Core.ObjectEntity;

namespace CodeStory.Core
{
	/// <summary>
	/// This httpmodule provide basic portlets navigation which was described by
	/// the <seealso cref="NavigationPortletAttribute"/>.
	/// </summary>
	public class PortletNavigateHttpModule : IHttpModule
	{
		#region IHttpModule Members
		public void Dispose() {
		}

		/// <summary>
		/// Initializes a module and prepares it to handle requests.
		/// </summary>
		/// <param name="context">An <see cref="T:System.Web.HttpApplication"></see> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
		public void Init(HttpApplication context) {
			context.BeginRequest += new EventHandler(BeginRequest);
		}

		/// <summary>
		/// Begins the request.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		private void BeginRequest(object sender, EventArgs e) {
			HttpApplication app = (HttpApplication)sender;
			string requestFileName = Path.GetFileName(app.Request.Url.AbsolutePath);
			if (requestFileName.EndsWith(".portlet.aspx", StringComparison.OrdinalIgnoreCase)) {
				string portletName = requestFileName.Substring(0, requestFileName.Length - 13);
				string pageid = GetPageIDByPortletName(portletName);
				if (!string.IsNullOrEmpty(pageid)) {
					string query = app.Request.Url.Query;
					string path = string.Format("~/default.aspx?pageid={0}", pageid);
					if (!string.IsNullOrEmpty(query)) {
						path += "&" + query.Substring(1);
					}
					app.Context.RewritePath(path);
				}
			}
		}

		public static Dictionary<string, string> portletInTabDictionary = new Dictionary<string, string>();

		/// <summary>
		/// Get pageid from the given name of the portlet.
		/// </summary>
		/// <param name="name">The name of the portlet.</param>
		/// <returns>The PageID of the Page which contains the portlet.</returns>
		private string GetPageIDByPortletName(string name) {
			string pageid = string.Empty;
			if (portletInTabDictionary.ContainsKey(name)) {
				pageid = portletInTabDictionary[name];
			} else {
				PortletNavigationObject obj = PortletNavigationObject.Read(name);
				if (obj != null) {
					pageid = obj.PageID.ToString();
					portletInTabDictionary[name] = pageid;
				}
			}
			return pageid;
		}
		#endregion
	}
}